<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * @throws CrowdvoxBridgeRequestException
 */
  class CrowdvoxBridgeRequest
  {
      private $accessToken;
      private $serverUrl;
      function __construct($crowdvoxServerUrl,$accessToken) 
      {
          $this->serverUrl = $crowdvoxServerUrl;
          $this->accessToken = $accessToken;
      }
      /**
       *This method expects json as result.
       * @param type $path
       * @param type $info 
       */
      //@todo add Https support
      function post($path,$info)
      {
          $serverUrl = $this->serverUrl.'/'.$path;
          $ch = curl_init($serverUrl);
          $options = array(
              CURLOPT_POST => true,
              CURLOPT_USERAGENT => "Crowdvox Bridge",
              CURLOPT_HTTPHEADER => array("X_Bridge_Token: ".$this->accessToken),
              CURLOPT_RETURNTRANSFER => true
          );
          $info = http_build_query($info);
          curl_setopt($ch,CURLOPT_POSTFIELDS ,$info);
          curl_setopt_array($ch, $options);
          $response = curl_exec($ch);
          $error = curl_errno($ch);
          $errorString = curl_error($ch);
          curl_close($ch);
          if($error)
          {
             throw new CrowdvoxBridgeRequestException($errorString,$error);
          }
          $response = json_decode($response,true);
          if(!$response['result'])
          {
              $errors = array();
              if($response['error'])
              {
                  $errors = $response['error'];
              }
              throw new CrowdvoxBridgeRequestException("Remote request error",CrowdvoxBridgeRequestException::ERROR_REQUEST,$errors);
          }
          return $response['data'];
      }
  }
  
  class CrowdvoxBridgeRequestException extends CrowdvoxBridgeException
  {
    const ERROR_REQUEST = 2;
    var $errors = array();
    function __construct($message = null, $code = null, $errors = null ,$previous = null) {
        
        $this->errors = $errors;
        parent::__construct($message, $code, $previous);
    }
  }
?>